package com.security.web.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.security.web.common.enums.HttpStatusCode;
import com.security.web.dao.SysUserDao;
import com.security.web.domain.JwtUser;
import com.security.web.entity.SysUser;
import com.security.web.service.SysUserService;
import com.security.web.utils.AjaxResult;
import com.security.web.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * 用户信息表(SysUser)表服务实现类
 *
 * @author makejava
 * @since 2022-01-07 10:36:09
 */
@Service("sysUserService")
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUser> implements SysUserService {

    @Resource
    SysUserDao userDao;

    @Resource
    UserDetailsService userDetailsService;

    @Resource
    PasswordEncoder passwordEncoder;

    @Resource
    JwtTokenUtil jwtTokenUtil;

    @Value("${jwt.tokenHead}")
    String tokenHead;

    @Override
    public JwtUser getUserByName(String username) {
        return new JwtUser(userDao.queryByLoginNameOne(username));
    }

    @Override
    public AjaxResult addUser(SysUser user) {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        user.setLoginName(user.getLoginName());
        user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
        user.setCreateTime(getWebsiteDatetime());
        int i = userDao.insert(user);
        if (i < 1) {
            return AjaxResult.error(HttpStatusCode.BAD_REQUEST);
        }
        return AjaxResult.success(HttpStatusCode.OK);
    }

    @Override
    public AjaxResult login(SysUser user, HttpServletRequest request) {
        //登录
        UserDetails userDetails = userDetailsService.loadUserByUsername(user.getLoginName());
        if (null == userDetails || !passwordEncoder.matches(user.getPassword(), userDetails.getPassword())) {
            return AjaxResult.error(400,"密码错误！请重新输入");
        }
        //更新security登录用户对象
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails
                , null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //生成token
        String token = jwtTokenUtil.generateToken(userDetails);

        Map<String, Object> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);
        return AjaxResult.success(HttpStatusCode.OK,tokenMap);
    }

    /**
     * 获取指定网站的日期时间
     *
     * @return 标准时间对象
     */
    private static Date getWebsiteDatetime() {
        try {
            URL url = new URL("https://www.baidu.com");// 取得资源对象
            URLConnection uc = url.openConnection();// 生成连接对象
            uc.connect();// 发出连接
            long ld = uc.getDate();// 读取网站日期时间
            Date date = new Date(ld);// 转换为标准时间对象
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);// 输出北京时间
            // return sdf.format(date);
            return date;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

